package com.wendy.controller;

import com.alibaba.fastjson.JSONObject;
import com.wendy.thirdpartyaccess.SocialConstants;
import com.wendy.thirdpartyaccess.wechat.AccessToken;
import com.wendy.thirdpartyaccess.wechat.WechatImpl;
import com.wendy.thirdpartyaccess.wechat.WechatUserInfo;
import com.wendy.utils.HttpClientUtils;
import com.wendy.utils.ResponseUtil;
import com.wendy.web.response.ResponseWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @author zhuwending
 */
@Controller
@Slf4j
public class SocialController {

    @Autowired
    private AccessToken accessToken;

    @RequestMapping(value = "/wechat/qrcode")
    @ResponseBody
    public ResponseWrapper wechatLogin() {
        return ResponseUtil.successResponse("qrcode", accessToken.getTicket());
    }

    @RequestMapping(value = "/wechat/userInfo")
    public String getUserInfo(HttpServletRequest request, Model model) {
        String code = request.getParameter("code");
        String state = request.getParameter("state");
        if (StringUtils.isEmpty(code) || StringUtils.isEmpty(state)) {
            throw new RuntimeException("非法请求");
        }
        String getAccessTokenUrl = SocialConstants.URL_ACCESS_TOKEN +
                "appid=" + SocialConstants.APP_ID +
                "&secret=" + SocialConstants.APP_SECRET +
                "&code=" + code +
                "&grant_type=authorization_code";
        JSONObject accessTokenObject = HttpClientUtils.httpGet(getAccessTokenUrl);
        String errcode = "errcode";
        if (accessTokenObject.containsKey(errcode)) {
            throw new RuntimeException("获取accessToken异常");
        }
        String accessToken = accessTokenObject.getString("access_token");
        String openid = accessTokenObject.getString("openid");
        WechatUserInfo userInfo = new WechatImpl(accessToken).getUserInfo(openid);
        log.info(userInfo.toString());
        model.addAttribute(userInfo);
        return "/page/index";
    }
}
